import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import { performance } from 'perf_hooks'; // 用于性能监控

@Middleware()
export class LoggingMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const start = performance.now(); // 记录请求的开始时间
      const { method, url } = ctx.request; // 获取请求的方法和 URL
      const ip = ctx.ip; // 获取请求的 IP 地址

      // 记录请求开始时的日志
      ctx.logger.info(`[START] ${method} ${url} - IP: ${ip}`);

      try {
        // 执行请求处理
        await next();

        // 记录请求结束时间和处理时长
        const end = performance.now();
        const duration = (end - start).toFixed(2); // 计算处理时长
        ctx.logger.info(`[END] ${method} ${url} - Duration: ${duration}ms - IP: ${ip}`);
      } catch (error) {
        // 记录错误日志
        const end = performance.now();
        const duration = (end - start).toFixed(2);
        ctx.logger.error(`[ERROR] ${method} ${url} - Duration: ${duration}ms - IP: ${ip} - Error: ${error.message}`);
        throw error; // 继续抛出错误，Midway 会处理它
      }
    };
  }

  static getName(): string {
    return 'logging';
  }
}
